Golang : Convert decimal number(integer) to IPv4 address
Problem :
You've read the previous tutorial on how to convert IPv4 address to decimal number and store into database. However, now you want to convert the decimal value back to IPv4 address. How to do that?
Solution :
Reverse the algorithm used in the conversion to decimal number. However, to get the correct result, we need to do two bit shifting and “0xff” masking.
For example :
package main
import (
"fmt"
"strconv"
)
func InttoIP4(ipInt int64) string {
// need to do two bit shifting and “0xff” masking
b0 := strconv.FormatInt((ipInt>>24)&0xff, 10)
b1 := strconv.FormatInt((ipInt>>16)&0xff, 10)
b2 := strconv.FormatInt((ipInt>>8)&0xff, 10)
b3 := strconv.FormatInt((ipInt & 0xff), 10)
return b0 + "." + b1 + "." + b2 + "." + b3
}
func main() {
// 1653276013 = 98.138.253.109
IPv4 := InttoIP4(1653276013)
fmt.Println(IPv4)
}
Output :
98.138.253.109
References :
https://processing.org/reference/bitwiseOR.html
http://stackoverflow.com/questions/12130464/ip-address-conversion-to-decimal-and-vice-versa
See also : Golang : Convert IPv4 address to decimal number(base 10) or integer
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.9k Golang : Print how to use flag for your application example
+13.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+9.1k Golang : Web(Javascript) to server-side websocket example
+10.5k Golang : Removes punctuation or defined delimiter from the user's input
+4.8k Golang : micron to centimeter example
+6.9k Golang : Gorrila mux.Vars() function example
+47.2k Golang : Convert int to byte array([]byte)
+14.2k Golang : GUI with Qt and OpenCV to capture image from camera
+8.5k Golang : Random integer with rand.Seed() within a given range
+19.2k Golang : Example for DSA(Digital Signature Algorithm) package functions
+13.3k Golang : Activate web camera and broadcast out base64 encoded images
+4.4k Adding Skype actions such as call and chat into web page examples